"""
get_h3c_filestorage_dir_stat()函数负责调用华三存储api，获取相应目录的容量

[z@test4 ~]$ python3 test.sh BigVote
161.56
[z@test4 ~]$ python3 test.sh vdncode
80.38
"""
# -*- coding:utf-8 -*-

import requests
import json
import sys
import re


# 调用华三集群的API，返回存储目录及使用情况
def get_h3c_filestorage_dir_stat(volume_name):
    # 拼接成登陆url
    base_url = "http://地址"
    request_url = "/api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username": "xx", "password": "xx"}

    # 登录请求
    res = requests.post(url=url, data=json.dumps(data), headers={'content-type': "application/json"})

    # 获取响应头信息
    set_cookie = res.headers.get('Set-Cookie')
    text_set_cookie = re.split('[;,=\']', set_cookie)

    # 从响应头信息中提取后面访问需要的cookie_value和x_xsrf_token_value
    xsrf_token_value = text_set_cookie[1].strip()
    cookie_value = 'calamari_sessionid=' + text_set_cookie[12] + ';' + 'XSRF-TOKEN=' + xsrf_token_value

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url

    cluster_res = requests.get(
        url=cluster_id_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成查询URL
    cluster_filestorage_dir_stat_1 = "/api/v3/onestor/"
    cluster_filestorage_dir_stat_2 = "/filestorage/dir/stat"
    cluster_filestorage_dir_stat = base_url + cluster_filestorage_dir_stat_1 + cluster_id + cluster_filestorage_dir_stat_2

    path = '/' + volume_name
    # 请求参数
    request_data = {
        "path": path,
        "type": "directory"
    }

    # 发送post请求，得到返回数据
    cluster_filestorage_dir_stat_res = requests.post(
        url=cluster_filestorage_dir_stat,
        data=json.dumps(request_data),
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })
    cluster_filestorage_dir_stat_data = cluster_filestorage_dir_stat_res.json()
    # 输出容量
    size = int(cluster_filestorage_dir_stat_data['data']['size'])

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
        url=logout_url,
        headers={
            'content-type': "application/json",
            'X-XSRF-TOKEN': xsrf_token_value,
            'Cookie': cookie_value,
        })

    return size


if __name__ == '__main__':
    
    h3c_xd_directory_capacity = get_h3c_filestorage_dir_stat(sys.argv[1])
    print(h3c_xd_directory_capacity)
